package com.hwn.datax.component;

import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeCell;

import java.util.List;

public class DynamicMenuTreeCell<T> extends TreeCell<T> {

    private ContextMenu contextMenu;

    private List<MenuItemData<T>> menuItemsData;

    public DynamicMenuTreeCell(List<MenuItemData<T>> menuItemsData) {
        this.menuItemsData = menuItemsData;
    }

    @Override
    protected void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            setText(null);
            setContextMenu(null);
        } else {
            initMenu();
            setText(item.toString()); // Assuming T has a meaningful toString method
            setContextMenu(contextMenu);
        }
    }

    public void initMenu() {
//        if (contextMenu != null) return;
        contextMenu = new ContextMenu();
        for (MenuItemData<T> data : menuItemsData) {
            if (data.getCondition().test(getItem())) {
                MenuItem menuItem = new MenuItem(data.getMenuText());
                menuItem.setStyle("-fx-padding: 0 18 0 18");
                menuItem.setOnAction(event -> data.getAction().accept(getItem()));
                contextMenu.getItems().add(menuItem);
            }
        }
    }
}